<?php

namespace App\Http\Controllers\Otc;

use App\Http\Controllers\Controller;
use App\Library\Yunxin;
use App\Models\AppealReplyImg;
use App\Models\Currency;
use App\Models\Property;
use App\Models\Recharge;
use App\Models\RechOrder;
use App\Models\User;
use App\Traits\YunXinTrait;
use DB;
use Exception;
use Illuminate\Http\Request;

class RechargeController extends Controller
{
    use YunXinTrait;

    /**
     * 商家发布的广告列表（C2C展示）.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function rech_orders(Request $request)
    {
        //默认展示卖出单
        $type = $request->get('type') ?? 2;
        //每页显示条数
        $pagesize = $request->get('pagesize') ?? 10;
        //用户ID
        $uid = $request->get('uid');

        if (!empty($uid)) {
            //查找用户
            $user = User::find($uid);
            //判断参数是否正确
            if (!$user) {
                //用户不存在
                return respF(1001);
            }
        }
        //查询记录
        $result = RechOrder::where('type', $type)->whereIn('status', [1, 2])->paginate($pagesize);
        //没有记录
        if (!$result) {
            //错误提示
            return respF(1009);
        }

        //拼装数据返回
        $data = [];
        //总记录条数
        $data['total'] = $result->total();
        //空数组
        $arr = [];
        //处理数据
        foreach ($result as $key => $value) {
            //商家id
            $arr[$key]['uid'] = $value->uid;
            //名称
            $arr[$key]['nickname'] = $value->user->nickname;
            //图片
            $arr[$key]['photo'] = config('alioss.host') . '/' . $value->user->headimg;
            //剩余数量
            $arr[$key]['num'] = $value->price_section;
            //订单id
            $arr[$key]['id'] = $value->id;
            //买卖类型
            $arr[$key]['type'] = $value->type;
        }

        $data['list'] = $arr;
        //如果uid有值
        if (isset($uid)) {
            //usdt的币种ID
            $cid = Currency::where('name_en', 'USDT')->value('id');
            //查找用户可用usdt资产
            $property = Property::where(['uid' => $uid, 'cid' => $cid])->value('balance');
            //组装
            $data['usdt_num'] = $property;
        }

        return response()->json(['status' => 1, 'msg' => '成功', 'data' => $data]);
    }

    /**
     * 保存订单提交.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function save_order(Request $request)
    {
        try {
            //验证必传参数
            if (!$request->has('total_price', 'bid', 'num', 'price', 'id', 'type', 'uid')) {
                throw new Exception(1003);
            }
            //接收参数
            $info = $request->all();
            //验证参数
            if (empty($info['total_price']) || empty($info['bid']) || empty($info['num'])
                || empty($info['id']) || empty($info['type']) || empty($info['uid'])
            ) {
                throw new Exception(1000);
            }
            //查找订单
            $real = RechOrder::where(['id' => $info['id']])->first();
            //不能自己买自己的单
            if ($real->uid == $info['uid']) {
                //不能购买自己发布的广告
                return respF(3022);
            }

            //验证交易限制(已购买用户购买)
            if ($real->trade_limit == 1) {
                //平台有过交易的用户(已完成)
                $trade_order = Recharge::where(['uid' => $info['uid'], 'status' => 3])->first();
                if (!$trade_order) {
                    //不支持新用户购买
                    throw new Exception(3018);
                }
            }
            //验证交易时间
            if ($real->trade_type == 1) {
                //时间区间转为数组
                $trade_time = explode('-', $real->trade_time);
                //当前时间
                $now_time = date('H:i', time());
                //不在区间
                if ($now_time < $trade_time[0] || $now_time > $trade_time[1]) {
                    //不在商家指定交易时间内
                    throw new Exception(3019);
                }
            }
            //查找用户
            $user = User::find($info['uid']);
            //用户不能是商家
            /*if ($user->type == 2) {
                throw new Exception(4005);
            }*/
            //判断实名
            if ($user->real_status != 2) {
                //实名认证未通过
                throw new Exception(2005);
            }

            //查找今日取消订单次数
            /*$cancels = Recharge::where(['uid' => $info['uid'], 'status' => 4])
            ->whereDate('created_at', date('Y-m-d', time()))->get();
            if ($cancels->count() >= 3) {
            //今日取消订单次数已达3次，限制购买
            return respF(3020);
            }*/

            //开启事务
            DB::beginTransaction();

            //type 1 用户买入 ，2 用户卖出 (这里的判断跟app不一样)
            if ($info['type'] == 2) {
                //用户交易密码
                $pay_pass = User::where(['id' => $info['uid']])->value('pay_pass');
                //验证交易密码
                if (md5($info['pay_pass']) != $pay_pass) {
                    //抛出错误
                    throw new Exception(2000);
                }
                //usdt ID
                $usdt_id = Currency::where('name_en', 'USDT')->value('id');
                //用户usdt资产
                $property = Property::where(['uid' => $info['uid'], 'cid' => $usdt_id])->first();

                if (collect($property)->count() == 0) {
                    
                    throw new Exception(2008);
                }
                //判断资产
                if ($property->balance < $info['num']) {
                    //用户资产不足
                    throw new Exception(2008);
                }
                //判断支付方式
                if (collect($user->user_alipay)->count() == 0 && collect($user->user_wechat)->count() == 0) {
                    //请绑定至少一种支付方式
                    throw new Exception(3016);
                }
                //冻结用户资产
                $property->decrement('balance', $info['num']);
                $property->increment('blocked', $info['num']);

                //提示一
                $msg_one = '您的订单已下单成功，请等待对方付款后发币';
                //提示二
                $msg_two = '您有一个新的订单，请尽快付款';
            } else {
                //提示一
                $msg_one = '您的订单已下单成功，请尽快付款';
                //提示二
                $msg_two = '您有一个新的订单，请等待对方付款后发币';
            }
            //验证剩余数量
            /*if ($real->surplus_num < $info['num']) {
            //抛出错误
            throw new Exception(1036);
            }*/
            //云信
            $model = new Yunxin\Yunxin();
            //发送信息
            $arr = $model->send_yx_msg($info['uid'], $info['bid'], $msg_one, $msg_two);
            //随机码
            $code = getCode();
            //拼装数组
            $data_info = [
                'uid'         => $info['uid'],
                'order_id'    => $info['id'],
                'num'         => $info['num'],
                'price'       => $info['price'],
                'total_price' => $info['total_price'],
                'bid'         => $info['bid'],
                'status'      => 1,
                'mark_no'     => $code,
                'type'        => $info['type'],
                'order_no'    => get_microtimes(),
            ];
            //减少订单剩余数量
            $real->decrement('surplus_num', $info['num']);
            //增加成交数量
            $real->increment('deal_num', $info['num']);
            //插入数据库
            $result = Recharge::create($data_info);
            //返回ID值
            $id['id'] = $result->id;

            DB::commit();

            return response()->json(['status' => 1, 'msg' => '下单成功', 'data' => $id]);
        } catch (Exception $e) {
            DB::rollback();
            //接收错误号
            $msg = $e->getMessage();

            return respF($msg);
        }
    }

    /**
     * 订单详情.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function order_info(Request $request)
    {
        //验证必传参数
        $oid = $request->get('oid');
        $uid = $request->get('uid');

        if (empty($oid) || empty($uid)) {
            return respF(1003);
        }

        //查询订单表
        $real = Recharge::where(['id' => $oid])->first();
        //验证订单
        if (collect($real)->count() == 0) {
            //返回错误
            return respF(1002);
        }
        //商家信息
        $seller = User::find($real->bid);
        //验证用户
        if (!$seller) {
            //返回错误
            return respF(3001);
        }
        //用户信息
        $buyer = User::find($real->uid);
        //验证用户
        if (!$buyer) {
            //返回错误
            return respF(3002);
        }
        //*****组装买家信息
        //会员uid
        $data['buyer']['uid'] = $buyer->id;
        //买家昵称
        $data['buyer']['nickname'] = $buyer->nickname;
        //买家头像
        $data['buyer']['headimg'] = config('alioss.host') . '/' . $buyer->headimg;
        //买家是否有支付宝
        $data['buyer']['alipay'] = $buyer->user_alipay()->select('alipay_account', 'alipay_code', 'real_name')->first();
        //买家是否有微信
        $data['buyer']['wechat'] = $buyer->user_wechat()->select('wechat_account', 'wechat_code', 'real_name')->first();
        //*****组装卖家信息
        //商家uid
        $data['seller']['uid'] = $seller->id;
        //卖家昵称
        $data['seller']['nickname'] = $seller->nickname;
        //卖家头像
        $data['seller']['headimg'] = config('alioss.host') . '/' . $seller->headimg;
        //卖家三十日成交额
        //$data['seller']['thirty_summary'] = $seller->thirty_summary->sum('total_price');
        //卖家真实姓名
        $data['seller']['name'] = $seller->autonym->name ?? '没有实名信息';
        //吱口令
        $data['seller']['squeak'] = $real->rech_order->squeak;
        //二维码
        $data['seller']['qr_code'] = config('alioss.host') . '/' . $real->rech_order->qr_code;
        //*****订单信息
        //交易金额(价格保留2位小数)
        $data['total_price'] = sprintf('%.2f', $real->total_price) ?? 0;
        //数量(数量保留6位小数)
        $data['num'] = sprintf('%.6f', $real->num) ?? 0;
        //单价(价格保留2位小数)
        $data['price'] = sprintf('%.2f', $real->price) ?? 0;
        //参考号
        $data['mark_no'] = $real->mark_no;
        //状态
        $data['status'] = $real->status;
        //订单号
        $data['order_no'] = $real->order_no;
        //创建时间
        $data['created_at'] = strtotime($real->created_at);
        //修改时间
        //$data['updated_at'] = strtotime($real->updated_at);
        //1为买入 2为卖出
        $data['type'] = $real->type;
        //确认付款时间
        //$data['pay_time'] = $real->pay_time;
        //商家电话
        //$data['phone'] = $real->enters->phone ?? null;
        //今日订单取消次数
        /*$count = Recharge::where(['uid' => $buyer->id, 'status' => 4])
        ->whereDate('created_at', date('Y-m-d', time()))->get();
        $data['cancel_num'] = $count->count();*/
        //申诉
        $appeal = $reply = [];
        if ($real->appeal_order) {
            $appeal['info'] = $real->appeal_order()->select('id', 'uid', 'type', 'content', 'status', 'expire_time', 'note')->first();
            $imgs           = $real->appeal_order->appeal_imgs()->select('img')->get();
            //处理图片
            foreach ($imgs as $img) {
                $img->img = config('alioss.host') . '/' . $img->img;
            }
            $appeal['imgs'] = $imgs;
            if (collect($real->appeal_order->appeal_reply)->count() > 0) {
                $reply = $real->appeal_order->appeal_reply()->select('id', 'uid', 'content', 'status', 'note')->first()->toArray();
                if (AppealReplyImg::where('reply_id', $reply['id'])->count() > 0) {
                    $img_reply = AppealReplyImg::where('reply_id', $reply['id'])->get();
                    //处理图片
                    foreach ($img_reply as $img) {
                        $img_r[] = config('alioss.host') . '/' . $img->img;
                    }
                    $reply['imgs'] = $img_r;
                }
            }
        }
        $data['appeal'] = $appeal;
        $data['reply']  = $reply;

        return response()->json(['status' => 1, 'msg' => '成功', 'data' => $data]);
    }

    /**
     * c2c订单列表(交易单列表).
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function rechorder_list(Request $request)
    {
        $info = $request->all();
        $data = [];
        if (empty($info['uid']) || empty($info['token'])) {
            return respF(1003);
        }

        if (empty($info['genre'])) {
            $info['genre'] = 0;
        }

        $where  = GetWhereGenre($info['genre'], $info['uid']);
        $result = Recharge::where($where)->where('status', '<>', 4)->where(function($query) use($request) {
                $order_no = $request->get('order_no');
                if ($order_no) {
                    $query->where('order_no', 'like', '%'.$order_no.'%');
                }
            })->orderby('created_at', 'DESC')->paginate(10);
        if ($info['genre'] == 4) {
            $result = Recharge::where($where)->whereIn('status', [5, 6])->where(function($query) use($request) {
                $order_no = $request->get('order_no');
                if ($order_no) {
                    $query->where('order_no', 'like', '%'.$order_no.'%');
                }
            })->orderby('created_at', 'DESC')->paginate(10);
        }

        $data['total'] = $result->total();

        if ($result->count() <= 0) {
            return respF(1009);
        }
        $list = [];
        foreach ($result as $k => $v) {
            $list[$k]['order_no']    = $v->order_no; //订单号
            $list[$k]['nickname']    = $v->seller->nickname; //名称
            $list[$k]['photo']       = config('alioss.host') . '/' . $v->seller->headimg; //名称
            $list[$k]['oid']         = $v->id; //订单id
            $list[$k]['type']        = $v->type ?? null; //1为用户卖 2为用户买
            $list[$k]['total_price'] = sprintf('%.2f', $v->total_price); //总价
            $list[$k]['status']      = $v->status; //状态
            $list[$k]['num']         = $v->num; 
            $list[$k]['created_at']  = strtotime($v->created_at); //创建时间
            $list[$k]['genre']       = HandleShowStatus($v->type, $v->status, 1); //类型
        }
        $data['list'] = $list;

        //获取USDT的logo
        $usdt = Currency::where('name_en', 'USDT')->first();
        if ($usdt) {
            $data['usdt_logo'] = config('alioss.host').$usdt->logo;
        }


        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }
}
